package com.coder.rental.controller;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.convert.NumberWithFormat;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.StrUtil;
import cn.hutool.jwt.JWTPayload;
import com.coder.rental.entity.Permission;
import com.coder.rental.entity.User;
import com.coder.rental.security.CustomerAuthenticationException;
import com.coder.rental.service.IUserService;
import com.coder.rental.utils.JwtUtils;
import com.coder.rental.utils.RedisUtils;
import com.coder.rental.utils.Result;
import com.coder.rental.utils.RouteTreeUtils;
import com.coder.rental.vo.RouteVO;
import com.coder.rental.vo.TokenVo;
import com.coder.rental.vo.UserInfoVo;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

@RestController
@RequestMapping("/rental/auth")
public class AuthController {

    @Resource
    private RedisUtils redisUtils;

    @Resource
    private IUserService userService;


    /**
     * 刷新token接口
     *
     * @param request HTTP请求对象，用于获取请求头或参数中的token
     * @return 返回刷新后的token信息
     */
    @PostMapping("/refreshToken")
    public Result refreshToken (HttpServletRequest request){
        // 获取token
        String token = request.getHeader("token");
        if(StrUtil.isEmpty(token)){
            token = request.getParameter("token");
        }
        // 获取当前认证信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        // 解析token获取用户名
        String username = JwtUtils.parseToken(token).getClaim("username").toString();
        String newToken = "";
        // 验证token中的用户名与当前用户是否一致
        if(StrUtil.equals(username,userDetails.getUsername())){
            // 创建新的token信息
            Map<String,Object> map =  new HashMap<>();
            map.put("username", userDetails.getUsername());
            newToken = JwtUtils.createToken(map);
        }else{
            throw new CustomerAuthenticationException("token数据异常");
        }
        // 获取本次token的过期时间
        NumberWithFormat claim = (NumberWithFormat) JwtUtils.parseToken(newToken).getClaim(JWTPayload.EXPIRES_AT);
        DateTime dateTime = (DateTime) claim.convert(DateTime.class, claim);
        long expireTime = dateTime.getTime();
        // 创建并设置新的token信息
        TokenVo tokenVo = new TokenVo();
        tokenVo.setToken(newToken).setExpireTime(expireTime);
        // 清除原有的token
        redisUtils.del("token:"+token);
        // 计算当前时间到token过期时间的秒数
        long nowTime = DateTime.now().getTime();
        String newTokenKey = "token:"+newToken;
        redisUtils.set(newTokenKey,newToken,(expireTime-nowTime)/1000);
        // 返回刷新后的token信息
        return Result.success(tokenVo).setMessage("刷新token成功");
    }

    // 响应用户信息请求
    @GetMapping("/getInfo")
    public Result getUseInfo(){
        // 从securityContextHolder 上下文中获取认证信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        // 如果认证信息为空，则返回失败响应
        if(authentication == null){
            return Result.fail().setMessage("认证信息为空");
        }
        // 从认证信息中提取用户对象
        User user = (User) authentication.getPrincipal();
        // 查询并获取用户的角色名称列表
/*        List<String> list = userService.selectRoleName(user.getId());
        Object[] array = list.toArray();// 将角色名称列表转换为数组*/
        List<Permission> permissionList = user.getPermissionList();
        Object[] array = permissionList.stream().filter(Objects::nonNull)
                .map(Permission::getPermissionCode)
                .toArray();

        // 将用户信息和角色权限信息封装到UserInfoVo对象中
        UserInfoVo userInfoVo = new UserInfoVo(user.getId(), user.getUsername(),
                user.getAvatar(),user.getNickname(),array);
        // 返回成功响应，包含用户信息
        return Result.success(userInfoVo).setMessage("获取用户信息成功");
    }

    @GetMapping("/menuList")
    public Result getMenuList(){
        // 获取当前用户信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if(authentication == null){
            return Result.fail().setMessage("认证信息为空");
        }
        User user = (User) authentication.getPrincipal();
        // 获取用户的权限列表
        List<Permission> permissionList = user.getPermissionList();

        // 获取用户菜单列表
        // 将permission_type 为2的按钮移除 不需要生成对应的菜单
        permissionList.removeIf(permission -> Objects.equals(permission.getPermissionType(),2));
        List<RouteVO> routeVOList = RouteTreeUtils.buildRouteTree(permissionList, 0);
        return Result.success(routeVOList).setMessage("获取菜单列表成功");
    }

    @PostMapping("/logout")
    public Result logout(HttpServletRequest request, HttpServletResponse response){
        String token = request.getHeader("token");
        if(StrUtil.isEmpty(token)){
            token = request.getParameter("token");
        }
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if(authentication != null){
            // 用户一旦登出，则清除redis中的token
            redisUtils.del("token"+token);
            SecurityContextLogoutHandler securityContextLogoutHandler = new SecurityContextLogoutHandler();
            securityContextLogoutHandler.logout(request, response, authentication);
            return Result.success().setMessage("登出成功");
        }
        return Result.fail().setMessage("登出失败");

    }

}
